const path = require('path');

function getModulePackageName(module) {
  if (!module.context) return null;

  const nodeModulesPath = path.join(__dirname, '../node_modules/');
  if (module.context.substring(0, nodeModulesPath.length) !== nodeModulesPath) {
    return null;
  }
  const moduleRelativePath = module.context.substring(nodeModulesPath.length);
  const [moduleDirName] = moduleRelativePath.split(path.sep);
  let packageName = moduleDirName;
  // handle tree shaking
  if (packageName && packageName.match('^_')) {
    packageName = packageName.match(/^_(@?[^@]+)/)[1];
  }
  return packageName;
}

const antCharts = [
  '@ant-design/charts',
  '@ant-design/graphs',
  '@ant-design/maps',
  '@ant-design/plots',
  '@antv',
];

export default function (memo) {
  memo.optimization.splitChunks({
    chunks: 'async',
    minSize: 10000,
    minChunks: 1,
    maxAsyncRequests: 5,
    automaticNameDelimiter: '~',
    cacheGroups: {
      vendors: {
        name: 'vendors',
        priority: -5,
        test: (module) => {
          const packageName = getModulePackageName(module);
          if (packageName) {
            return antCharts.indexOf(packageName) === -1;
          }
          return false;
        },
      },
      viz: {
        name: 'viz',
        priority: -10,
        test: (module) => {
          const packageName = getModulePackageName(module);
          if (packageName) {
            return antCharts.indexOf(packageName) >= 0;
          }
          return false;
        },
      },
      common: {
        name: 'common',
        minChunks: 3,
        priority: -20,
        reuseExistingChunk: true,
      },
    },
  });
}
